<template>
  <div class="rule-box">
    <div v-if="$route.query.type" class="back-title">
      <i class="el-icon-arrow-left" @click="$router.go(-1)">返回</i>
    </div>
    <div class="container">
      <div class="container-body">
        <div class="title-box flex">
          <div class="container-title">{{ $route.query.title }}</div>
          <div class="container-btn">
            <el-button v-if="$route.query.type != 'view'" @click="handleShowRemark">评论</el-button>
            <!--  v-if="$route.query.title == 'handle'"  或是 'edit' -->
            <el-button v-if="$route.query.type=='handle'" @click="handlesaveWork('generateForm')">提交</el-button>
            <el-button v-if="$route.query.type=='handle'" @click="handleSaveDraft">保存</el-button>
            <el-button
              v-if="$route.query.type == 'handle' && dataInfo.isReject == 1"
              @click="handleRejectWork"
            >驳回</el-button>
            <el-button @click="handleFlowView">查看流程</el-button>
          </div>
        </div>
        <div class="container-row">
          <div class="container-list flex">
            <div class="img-list flex">
              <img :src="require('@/assets/images/workbench/list1.png')" alt="">
              <div class="">
                <p class="status-box box-blue">
                  {{
                    dataInfo.orderStatus == -1
                      ? "已删除"
                      : dataInfo.orderStatus == 1
                        ? "处理中"
                        : dataInfo.orderStatus == 2
                          ? "已完成"
                          : dataInfo.orderStatus == 4
                            ? "已挂起"
                            : "已撤销" || "--"
                  }}
                </p>
                <p>状态</p>
              </div>
            </div>
            <div class="img-list flex">
              <img :src="require('@/assets/images/workbench/list2.png')" alt="">
              <div>
                <p class="status-box box-lighblue">
                  {{ dataInfo.currentUserName || "--" }}
                </p>
                <p>当前处理人</p>
              </div>
            </div>
            <div class="img-list flex">
              <img :src="require('@/assets/images/workbench/list3.png')" alt="">
              <div>
                <p class="status-box box-blue">
                  {{
                    dataInfo.currentTaskPriority == 0
                      ? "极低"
                      : dataInfo.currentTaskPriority == 1
                        ? "低"
                        : dataInfo.currentTaskPriority == 2
                          ? "中"
                          : dataInfo.currentTaskPriority == 3
                            ? "高"
                            : dataInfo.currentTaskPriority == 4
                              ? "极高"
                              : "--"
                  }}
                </p>
                <p>优选级</p>
              </div>
            </div>
            <div class="img-list flex">
              <img :src="require('@/assets/images/workbench/list4.png')" alt="">
              <div>
                <p class="status-box box-lighblue">
                  {{ dataInfo.orderTaskName || "--" }}
                </p>
                <p>当前步骤</p>
              </div>
            </div>
          </div>
          <div class="container-list">
            <el-collapse v-model="activeNames" accordion>
              <el-collapse-item name="1">
                <template slot="title">
                  <span style="font-size: 14px; font-weight: bold">基础信息</span>
                </template>
                <noStyleDetail
                  :details-list="detailsList"
                  :form-data="dataInfo"
                />
              </el-collapse-item>
            </el-collapse>
          </div>
          <div class="container-list">
            <div class="form-list">
              <el-tabs v-model="activeName" @tab-click="handleFormTabs(activeName)">
                <el-tab-pane
                  v-for="(item, index) in formInstances"
                  :key="'tab'+item.formName+index"
                  :label="item.formName"
                  :name="item.formId"
                >
                  <!--   不仅要判断是否有ID还要判断是否是查看详情  -->
                  <!-- <noStyleDetail
                v-if="(item.id || $route.query.type == 'view') || index!==formInstances.length-1"
                :details-list="formDetailsLists[index]"
                :form-data="setFormData(item.formData, formDetailsLists[index])"
              /> -->
                  <div>
                    <my-generate-form
                      v-if="isShowForm"
                      ref="generateForm"
                      :data="JSON.parse(item.formContent)"
                      :value="item.formData?JSON.parse(item.formData):{}"
                      :remote="remoteFuncs[index]"
                      :disabled="$route.query.type == 'view' || !item.canEdit"
                    />
                    <!-- @on-change="handleGenerateChage" -->
                  </div>
                  <template v-if="item.hasfiles">
                    <div v-for="(i,inx) in fileInfo" :key="i.file_name+inx">
                      <a class="file-link" :href="defaultUrl+i.file_path">{{ i.file_name }}</a>
                    </div>
                  </template>
                  <el-upload
                    v-if="isfileUpload==true && !item.id"
                    class="upload-demo"
                    :action="fileOpts.url"
                    :limit="fileOpts.limit"
                    :headers="fileOpts.headers"
                    :on-change="handleFileUploadProgress"
                    multiple
                    :file-list="fileList"
                    :on-exceed="handleExceed"
                    :on-error="handleError"
                    :on-success="handleSuccess"
                    accept=".zip,.docx,.xlsx"
                  >
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" style="margin-top:20px;font-size:14px;"><span>支持扩展名：{{ fileOpts.accept }}</span></div>
                  </el-upload>
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
          <div class="container-list">
            <el-tabs
              v-model="activeLogName"
              @tab-click="handleChange(activeLogName)"
            >
              <!--  评论  -->
              <el-tab-pane label="评论" name="first">
                <div v-if="comments.length > 0" class="remark-record">
                  <div v-for="(i, inx) in comments" :key="i.userName+inx" class="recod-list">
                    <div>{{ i.userName }} {{ i.createTime }}</div>
                    <div>{{ i.content }}</div>
                  </div>
                </div>
                <hk-form
                  v-if="isShowComments"
                  ref="hkFormRef"
                  label-width="0"
                  :form-labels="remarkFormObj.formLabels"
                  :data="formData"
                  :btn-hidden="false"
                  @handleSubmitEvent="handleSubmitEvent"
                  @handleCancel="handleCancel"
                />
              </el-tab-pane>
              <!-- 历史记录 -->
              <el-tab-pane label="历史记录" name="second">
                <div v-for="(item, index) in history" :key="'history'+index">
                  <div class="recod-list">
                    <div>{{ item.userName }} {{ item.createTime }}</div>
                    <div>动作:{{ item.actionName }}</div>
                    <div v-for="(i, inx) in item.orderHistoryActions" :key="inx">
                      <div v-if="!i.showContent">
                        {{ i.actionType }}:{{ i.actionContent }}
                      </div>
                      <div v-else>{{ i.showContent }}</div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
              <!--  SLA -->
              <el-tab-pane label="SLA列表" name="third" />
            </el-tabs>
          </div>
        </div>
      </div>
      <remark-dialog
        ref="remarkDialogRef"
        @handleSubmit="handleSubmitRemark"
      />
      <reject-dialog
        ref="rejectDialogRef"
        @handleSubmit="handleRejectNode"
      />
    </div>
  </div>
</template>
<script>
import HkForm from '@/components/HkForm'
import noStyleDetail from '@/components/HkDetails/noStyleDetail'
import remarkDialog from './remarkDialog.vue'
import rejectDialog from './rejectDialog.vue'
import MyGenerateForm from './components/GenerateForm'

import {
  queryDetail,
  queryHistory,
  addComment,
  executeWork,
  saveDraft,
  getNextNodeInfo,
  rejectWork
} from '@/api/workbench/workbenchList.js'
import { get, post } from '@/utils/request'
import { setJsonLists, isfileUpload } from '@/views/basicConfig/serviceConfig/utils/setArr.js'
import { getToken } from '@/utils/auth'
const BASE_URL = window.baseUrl.ticket
export default {
  components: { HkForm, remarkDialog, noStyleDetail, MyGenerateForm, rejectDialog },
  beforeRouteLeave(to, from, next) {
    from.meta.keepAlive = false
    next()
  },
  props: {
    title: {
      type: String,
      default() {
        return '新建'
      }
    }
  },
  data() {
    return {
      open: false,
      detailsData: { sponsor: 'admin', team: '1111', organ: 'baolande' },
      dataInfo: {
        orderStatus: '状态'
      },
      activeName: null,
      formInstances: [],
      formDetailsLists: [],
      activeLogName: 'first',
      formData: {},
      remarkFormObj: {
        formLabels: [
          {
            label: '',
            field: 'comment',
            type: 'textarea',
            attrs: {
              rows: 10,
              cols: 30,
              placeholder: '请输入',
              maxLength: 255
            },
            span: 24
          }
        ]
      },
      //  评论记录
      comments: [
        {
          name: 'Admin',
          content: 'aaaa',
          createTime: 1675934942589
        }
      ],
      isShowComments: false,
      //  历史记录
      history: [
        {
          action: 0,
          actionName: '提交',
          actionType: 'CREATE',
          createTime: 1675665355635,
          formInstance: null,
          icon: null,
          userName: 'admin',
          id: '7585a9662fed6f3fea61ee32094e1b9e',
          orderHistoryActions: [
            {
              id: '31e147819fe4670dc20b340d4772dd0b',
              orderId: '82372176-a5e8-11ed-b14c-52540004bcb4',
              orderHistoryId: '7585a9662fed6f3fea61ee32094e1b9e',
              sort: 0,
              createTime: 1675665355635,
              actionType: '填写了表单',
              actionContent: 'HK发起工单表单',
              orderStatus: null,
              showContent: null
            },
            {
              id: '01b171b13ddcb1ec8a133189228a8736',
              orderId: '82372176-a5e8-11ed-b14c-52540004bcb4',
              orderHistoryId: '7585a9662fed6f3fea61ee32094e1b9e',
              sort: 1,
              createTime: 1675665355635,
              actionType: '自动分配',
              actionContent: '工单处置,5c1ecb5d-ab10-4f96-968b-08ad2ac78993',
              orderStatus: null,
              showContent: '自动分配节点(工单处置)处理人: null'
            }
          ]
        }
      ],
      //  基础信息
      detailsList: [
        { label: '流水号', field: 'serialNumber', span: 12 },
        { label: '服务', field: 'flowName', span: 12 },
        { label: '发起人', field: 'createUserName', span: 12 },
        { label: '发起时间', field: 'createTime', span: 12 },
        { label: '团队', field: 'team', span: 12 },
        { label: '部门', field: 'class', span: 12 },
        { label: '组织', field: 'dept', span: 12 }
      ],
      activeNames: '1',
      designFormData: {},
      viewAllData: {},
      remoteObjs: [],
      remoteFuncs: [],
      isShowForm: false,
      isfileUpload: false,
      fileList: [],
      fileOpts: {
        url: window.baseUrl.ticket + '/attachment/upload',
        limit: 3,
        accept: 'zip,docx,xlsx',
        params: 'files',
        headers: { Authorization: 'Bearer ' + getToken() }
      },
      fileInfo: [],
      defaultUrl: window.defaultUrl,
      lists: null,
      uploadFiles: []
    }
  },
  mounted() {
    this.getQueryDetail(this.$route.query.serialNumber)
  },
  methods: {
    //  设置动态获取的form表单
    async setRemoteFunc(param, index) {
      const _self = this
      this.remoteFuncs[index] = {}
      const remoteObjs = []
      const newArr = await setJsonLists(param)
      //  判断是否有上传附件
      _self.isfileUpload = await isfileUpload(newArr)
      newArr.forEach(i => {
        if (i.type == 'cascader' || i.type == 'radio' || i.type == 'select' || i.type == 'checkbox') {
          if (i.options.remote == true) {
            remoteObjs.push({ remoteFunc: i.options.remoteFunc, props: i.options.props })
          }
        }
      })
      if (remoteObjs.length > 0) {
        remoteObjs.forEach(i => {
          this.remoteFuncs[index][i.remoteFunc] = function(resolve) {
            const reg = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/g
            const reg2 = /^\//g
            if (/^post\(.*\)$/.test(i.remoteFunc)) {
              const match = /^post\('(.*)'(?:,'\{.*\}')?\)$/.exec(i.remoteFunc)
              if (match) {
                const url = match[1]
                const param = match.length > 1 ? match[2] : {}
                post(url, param).then(res => {
                  resolve(res)
                })
              }
            } else if (reg.test(i.remoteFunc)) {
              get(i.remoteFunc).then(res => {
                resolve(res)
              })
            } else if (reg2.test(i.remoteFunc)) {
              get(BASE_URL + i.remoteFunc).then(res => {
                resolve(res)
              })
            } else {
              _self.$message.error('请配置正确的远端方法')
            }
          }
        })
      }
      if ((this.formInstances.length - 1) == index) {
        this.isShowForm = true
      }
    },
    //  获取详情信息
    getQueryDetail(param) {
      queryDetail({ serialNumber: param }).then(async(res) => {
        this.viewAllData = res
        //  评论
        this.comments = res.comments
        //  文件上传的信息
        this.fileInfo = JSON.parse(res?.formData).attachment || []
        if (this.fileInfo.length > 0) {
          this.fileList = JSON.parse(res?.formData).attachment.map(i => {
            return { name: i.file_name, url: i.file_path }
          })
        }
        // 表单内容
        this.formInstances = res.formInstances
        if (res.formInstances.length > 0) {
          this.formInstances.forEach((i, index) => {
            if (JSON.parse(i.formData)?.attachment?.length > 0) {
              this.formInstances[index].hasfiles = true
            } else {
              this.formInstances[index].hasfiles = false
            }
          })
          if (this.$route.query.type === 'view') {
            // this.isShowForm = true
            this.activeName = res.formInstances[0].formId
          } else {
            this.activeName =
              res.formInstances[res.formInstances.length - 1].formId
          }
          await res.formInstances.forEach(async(i, index) => {
            await this.setRemoteFunc(JSON.parse(i.formContent)?.list, index)
          })

          //  重置表单数据
          this.formDetailsLists = []
          res.formInstances.forEach(async(i) => {
            const lists = await setJsonLists(JSON.parse(i.formContent)?.list)
            if (lists.length > 0) {
              const arr = lists.map((item) => {
                return { label: item.name, field: item.model, span: 12 }
              })
              this.formDetailsLists.push(arr)
            }
          })
        }
        this.dataInfo = res
      })
    },
    //  点击展示评论
    handleShowRemark() {
      this.isShowComments = !this.isShowComments
      const container = document.querySelector('.container-body')
      if (this.isShowComments) {
        setTimeout(function() {
          container.scrollTop = container.scrollHeight
          console.dir(container.scrollTop)
        }, 0)
      }
    },
    //  点击评论按钮
    handleClickRemark() {
      this.$refs.remarkDialogRef.show()
    },
    //  评价、历史记录、SLA列表切换
    handleChange(currentStep) {
      if (currentStep == 'second') {
        queryHistory({ serialNumber: this.$route.query.serialNumber }).then(
          (res) => {
            this.history = res
          }
        )
      }
    },
    //  表单tab页切换
    async handleFormTabs(tab) {
      const currenTabData = this.formInstances.filter(i => {
        return i.formId == tab
      })
      this.fileInfo = JSON.parse(currenTabData[0]?.formData)?.attachment || []
    },
    //  评论编辑保存
    handleSubmitEvent(val) {
      if (val.content == '') {
        this.$message.error('评论不能为空')
        return
      }
      addComment({ serialNumber: this.$route.query.serialNumber, ...val }).then(
        (res) => {
          this.comments = res
          this.$message.success('评论成功!')
          this.formData = {}
        }
      )
    },
    //  点击评论取消
    handleCancel() {
      this.isShowComments = false
    },
    //  表单值为null时,设置表单详情
    setFormData(formData, currentDetailsList) {
      if (formData) {
        return JSON.parse(formData)
      } else {
        if (currentDetailsList) {
          const fieldArr = currentDetailsList.map((i) => {
            return i.field
          })
          const data = {}
          fieldArr.forEach((i) => {
            data[i] = null
          })
          return data
        }
      }
    },
    //  点击保存草稿箱
    handleSaveDraft() {
      saveDraft({
        flowId: this.viewAllData.flowProcessId,
        orderTitle: this.viewAllData.orderTitle,
        serviceId: this.viewAllData.serviceId,
        formData: JSON.stringify(this.designFormData)
      }).then((res) => {
        this.$message.success('保存成功，请到草稿箱查看')
        this.$router.go(-1)
      })
    },
    //  提交工单
    handlesaveWork(generateForm, validate = true) {
      this.$refs?.generateForm[this.formInstances.length - 1].getData(validate).then((data) => {
        this.designFormData = data
        getNextNodeInfo({ flowId: this.viewAllData.flowProcessId, taskId: this.viewAllData.taskKey }).then((res) => {
          if (res.length > 0 && res[0].nodeAssignWay !== 'autoAssign') {
            this.$refs.remarkDialogRef.show('选择下级处理人', res)
          } else {
            this.saveData({})
          }
        })
      })
    },
    //  点击提交评论弹窗
    handleSubmitRemark(val) {
      this.handleExecuteWork(val)
    },
    //  工单执行
    handleExecuteWork(data) {
      //  弹窗数据处理
      let assignUserMap = {}
      for (const key in data) {
        if (key !== 'comment') {
          assignUserMap = { [key]: [data[key]] }
        }
      }
      this.saveData(assignUserMap)
    },
    //  提交接口
    saveData(assignUserMap) {
      if (this.uploadFiles.length > 0) {
        this.fileInfo = []
        this.uploadFiles.forEach(i => {
          this.fileInfo.push(i.response.data[0])
        })
      }
      executeWork({
        formData: JSON.stringify({ ...this.designFormData, attachment: this.fileInfo }),
        comment: '',
        serialNumber: this.$route.query.serialNumber,
        assignUserMap: assignUserMap || {}
      }).then((res) => {
        this.$message.success('提交成功')
        this.$router.go(-1)
      })
    },
    //  查看流程
    handleFlowView() {
      this.$router.push({ path: window.prefix + '/bpmn/processDesign/addProcess', query: { type: 'view', flowId: this.viewAllData.flowProcessId, taskKey: this.viewAllData.taskKey || 1 }})
    },
    // 发生改变
    handleFileUploadProgress(file, fileList) {
      this.fileList = fileList.slice(-3)
    },
    // 文件数量超过3条
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },

    //  上传成功
    handleSuccess(success, file, fileList) {
      if (success.code == 200) {
        this.$message.success('上传成功')
        this.uploadFiles = fileList
      } else {
        this.$message.error(success.msg)
      }
    },
    //  表单元素发生变化
    handleGenerateChage(field = '', value = '', data = {}) {
      console.log('表单元素发生变化了-------', data)
      this.formInstances[this.formInstances.length - 1].formData = JSON.stringify(data)
    },
    //  点击驳回按钮
    handleRejectWork() {
      this.$refs.rejectDialogRef.show('选择驳回节点', this.viewAllData.rejectNodes)
    },
    // 选择驳回节点之后
    handleRejectNode(data) {
      rejectWork({ serialNumber: this.$route.query.serialNumber, targetNodeId: data.targetNodeId }).then(res => {
        this.$message.success('驳回成功')
        this.$router.go(-1)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
#app.dark-theme{
  .el-collapse-item__heade,.el-collapse-item__content{
    padding-left:10px !important;
  }
  .container-list{
    color:#fff;
  }
  .recod-list>div:nth-of-type(2){
    color:#00e1e4!important;
  }
}
::v-deep .el-form-item {
  margin-bottom: 20px !important;
}
.rule-box{
  overflow:hidden;
}
.container {
  position: relative;
  height: calc(100% - 40px);
  background: #fff;
  .container-body {
    height: 100%;

    .title-box {
      padding: 20px;
      align-items: center;
      border-bottom: 1px solid rgba(0, 0, 0, 0.08);
      .container-title {
        flex: 1;
        font-size: 20px;
        color: #666;
      }
    }
    .container-row{
      height:calc(100% - 77px);
      overflow-y:auto;
    }
  }
  .container-footer {
    background: #fff;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    width: 100%;
    text-align: right;
    padding: 20px;
  }
  .container-list {
    padding: 20px;
    background: #fff;
    border-radius: 4px;
    padding: 20px;
    .file-link{font-size:14px;display:inline-block;padding:10px 0;color:#4B6EEF;}
    .img-list {
      align-items: center;
      flex: 1;
      width: 25%;
      img {
        width: 60px;
        height: 60px;
        margin-right: 10px;
      }
      > .div {
        width: calc(100% - 70px);
      }
      .status-box {
        font-size: 14px;
        color: #fff;
        border-radius: 4px;
        padding: 5px 10px;
        max-width: 200px;
        text-align: center;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      .box-blue {
        background: #68bcfe;
      }
      .box-lighblue {
        background: #6e8af1;
      }
    }
    .title {
      font-size: 14px;
      font-weight: bold;
      margin-bottom: 20px;
    }
    .recod-list {
      border-bottom: 1px solid #ccc;
      > div {
        padding: 10px 10px;
        font-size: 14px;
        &:nth-child(2) {
          color: #0d1cf1;
        }
      }
    }
  }
}

.tips {
  margin-left: 10px;
  border-left: 4px solid #1890ff;
}
</style>
